// 参考自: https://segmentfault.com/q/1010000010946758
// 在mac的safari上使用localstorage时报了"the operation is insecure"的错误

import { message } from 'antd';

const funcUrl = file => {
  let url = window.location.origin;
  if (process.env.NODE_ENV === 'development') {
    // 开发环境
    url += file;
  } else {
    // 生产环境
    let url2 = window.location.pathname;
    if (url2 !== '/') {
      url2 = url2.substr(0, url2.lastIndexOf('/'));
    }
    url += url2 + file;
  }
  return url;
};

export function getAuthority() {
  try {
    return document.cookie && window.sessionStorage
      ? sessionStorage.getItem('antd-pro-authority')
      : 'guest';
  } catch (e) {
    message.error(e.toString());
  }
}

export function setAuthority(response, userName) {
  // 保存用户信息
  sessionStorage.setItem('token', response.token || 'emptyToken');
  sessionStorage.setItem('userId', response.userId || 0);
  sessionStorage.setItem('name', response.name || '管理员');
  sessionStorage.setItem('userName', userName || 'admin');
  sessionStorage.setItem(
    'headPortrait',
    response.avatar || funcUrl('/static/BiazfanxmamNRoxxVxka.png')
  );
  sessionStorage.setItem('notifyCount', response.notifyCount || 0);
  return sessionStorage.setItem('antd-pro-authority', 'admin');
}
